package setting

import (
	"../common"
	"../web"
	"strings"
)

type SetRepairObj struct {
	common.BaseHandler
}

type RepairSetQueryObj struct {
	common.BaseHandler
}

func (self *SetRepairObj) Prepare() {
	stations := *common.FetchAllRowsPtr(
		`SELECT STATION
           FROM SFC_STATION(NOLOCK) 
          ORDER BY STATION`,
		self.Usr.Conn, new(common.RecDataStr))
	repairs := *common.FetchAllRowsPtr(
		`SELECT DISTINCT PROCESS 
		   FROM SFC_REPAIRSETTING(NOLOCK)`,
		self.Usr.Conn, new(common.RecDataStr))

	self.TmplData["stations"] = stations
	self.TmplData["repairs"] = repairs
}

func (self *SetRepairObj) ParameterCheck() bool {
	c_name := strings.TrimSpace(self.Ctx.Params["procname"])
	c_acte := strings.TrimSpace(self.Ctx.Params["acteng"])
	c_actc := strings.TrimSpace(self.Ctx.Params["actchn"])
	c_stat := strings.TrimSpace(self.Ctx.Params["cyclstat"])
	if c_name == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please input the name.")
		return false
	}
	if c_acte == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please input the Repair Action(ENG).")
		return false
	}
	if c_actc == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please input the Repair Action(CHN).")
		return false
	}
	if c_stat == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please select the Recycle Station.")
		return false
	}

	self.Sqlparas = append(self.Sqlparas, c_name)
	self.Sqlparas = append(self.Sqlparas, c_acte)
	self.Sqlparas = append(self.Sqlparas, c_actc)
	self.Sqlparas = append(self.Sqlparas, c_stat)
	self.Sqlparas = append(self.Sqlparas, self.Usr.Username)
	self.Flashparas = []interface{}{c_name}

	return true
}

func (self *SetRepairObj) SqlExecute() bool {
	spRtnData := *common.FetchOneRowPtr(
		`sp_SetRepair ?, ?, ?, ?, ?`,
		self.Usr.Conn, new(common.SPReturn), self.Sqlparas...)
	if spRtnData.(common.SPReturn).Flag > 0 {
		self.TmplData["error"] = common.GetTextSP(self.Lang, spRtnData)
		return false
	}
	return true
}

func RepairSetHandler(ctx *web.Context) {
	self := new(SetRepairObj)
	self.Ctx = ctx
	self.Url = "/setrepair"
	self.Html = "setrepair.html"
	self.Rightlist = []string{"setrepair"}
	self.Flashstr = "Set Repair: [ %s ] finished."
	self.Do(self)
}

func (self *RepairSetQueryObj) ParameterCheck() bool {
	s_proc := self.Ctx.Params["q"]

	self.Sqlparas = append(self.Sqlparas, s_proc)

	return true
}

func (self *RepairSetQueryObj) SqlQueryExecute() {
	rprset := *common.FetchAllRowsPtr(
		`SELECT ROW_NUMBER() OVER(ORDER BY IDX),PROCESS,ACTION_ENG,ACTION_CHN,CYCLE_STATION 
		   FROM SFC_REPAIRSETTING(NOLOCK) 
		  WHERE PROCESS=?`,
		self.Usr.Conn, new(common.RepairSetting), self.Sqlparas...)
	self.TmplData["rprset"] = rprset
	self.TmplData["procname"] = self.Sqlparas[0].(string)
}

func GetRepairSetHandler(ctx *web.Context) {
	self := new(RepairSetQueryObj)
	self.Ctx = ctx
	self.Html = "rprsetdetail.html"
	self.DoQueryUrl(self)
}
